import { Body, Controller, Get, Param, Post, UseGuards } from '@nestjs/common';
import { DormitoryService } from './dormitory.service';
import { UseLog } from 'src/log/useLog.decorator';
import { UserGuard } from 'src/role/role.guard';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { Dormitory } from './dormitory.entity';
import { CurrentUser } from 'src/user/user.decorator';
import { UserSys } from 'src/user/userSys.entity';
import { FindOptionsWhere } from 'typeorm';
import { RoleEnum } from 'src/role/role.enum';

@Controller('api/dormitory')
@ApiTags("宿舍")
@UseGuards(AuthGuard("jwt"))
export class DormitoryController {
    constructor(
        private readonly dormitoryService: DormitoryService
    ) { }

    @Post("add")
    @UseLog("添加宿舍")
    @UseGuards(UserGuard([]))
    public add(
        @Body() body: Dormitory,
        @CurrentUser() user: UserSys
    ) {
        const entity = this.dormitoryService.dormitory.create(body);
        entity.user = user;
        entity.system = user.system;
        return this.dormitoryService.dormitory.save(entity);
    }

    @Get("get")
    @ApiOperation({ summary: "获取宿舍" })
    @UseGuards(UserGuard([]))
    public get(
        @CurrentUser() user: UserSys
    ) {
        const where: FindOptionsWhere<Dormitory> = {};
        if (user.role !== RoleEnum.boos) {
            where.system = {
                id: user.system.id
            }
        }
        return this.dormitoryService.dormitory.find({
            order: {
                id: "desc"
            },
            where,
            relations: ["user", "system"]
        })
    }

    @Post(":id/upd")
    @UseLog("修改宿舍")
    @UseGuards(UserGuard([]))
    public upd(
        @Param("id") id: number,
        @Body() data: Dormitory
    ) {
        return this.dormitoryService.dormitory.update({ id }, data)
    }

    @Post("del")
    @UseLog("删除宿舍")
    @UseGuards(UserGuard([]))
    public del(
        @Body() { ids }
    ) {
        return this.dormitoryService.dormitory.delete(ids)
    }

}
